package com.leenmvc.core.web.controller;

import com.leenmvc.core.annotation.ApiDescription;
import com.leenmvc.core.annotation.Note;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.utils.DateUtils;
import com.leenmvc.core.utils.MysqlImportUtil;
import com.leenmvc.core.base.result.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Map;

/**
 * @Author: zhousc
 * @Description:
 * @date: 2020/8/19 9:15
 */
@RestController
@ApiDescription("mysql导入导出")
@RequestMapping("system/mysqlImport")
public class MysqlImportController {


    @GetMapping("export")
    @Note("备份文件导出,导出到本地")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response){
        String osName = System.getProperty("os.name");
        // 临时文件
        String filePath;
        if (osName.toLowerCase().contains("windows")){
            filePath = "c:/dbImprot.sql";
        } else {
            filePath = "/dbImprot.sql";
        }
        BufferedInputStream bif = null;
        BufferedOutputStream bof = null;
        try {
            MysqlImportUtil.backup(filePath);
            String date = DateUtils.format(new Date(), DateUtils.DATE_PATTERN);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;filename="+MysqlImportUtil.dbName+date+".sql");
            ServletOutputStream outputStream = response.getOutputStream();
            bif = new BufferedInputStream( new FileInputStream(filePath));
            bof = new BufferedOutputStream(outputStream);
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = bif.read(buffer)) > 0) {
                bof.write(buffer, 0, len);
                bof.flush();
            }
            bif.close();
            bof.close();
            // 下载完成，删除文件
            File file = new File(filePath);
            if (file.exists()){
                if (file.delete()){
                    System.out.println(file.getName() + " 文件已被删除！");
                }else {
                    System.out.println("文件删除失败！");
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("importFileReductionDb")
    @Note("上传备份文件，完成数据库还原功能")
    public Result importFileReductionDb(@RequestParam MultipartFile file){
        if (file.isEmpty()) {
            throw new BusinessException("上传文件为空");
        }
        // 临时文件
        String osName = System.getProperty("os.name");
        String filePath;
        if (osName.toLowerCase().contains("windows")){
            filePath = "c:/dbreduction.sql";
        } else {
            filePath = "/dbreduction.sql";
        }
        InputStream inputStream = null;
        BufferedInputStream bif = null;
        BufferedOutputStream bof = null;
        try {
            inputStream = file.getInputStream();
            bif = new BufferedInputStream(inputStream);
            bof = new BufferedOutputStream(new FileOutputStream(filePath));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bif.read(bytes)) != -1){
                bof.write(bytes,0,len);
                bof.flush();
            }
            // 开始还原数据库
            MysqlImportUtil.load(filePath);

            // 关闭io
            bif.close();
            bof.close();

            // 删除文件
            File tempFile = new File(filePath);
            if (tempFile.exists()){
                if (tempFile.delete()){
                    System.out.println(tempFile.getName() + " 文件已被删除！");
                }else {
                    System.out.println("文件删除失败！");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            try {
                bif.close();
                bof.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Result();
    }


    @PostMapping("importUrlDb")
    @Note("通过日期还原数据库，前端选择日期")
    public Result importUrlDb(@RequestParam long time){
        String date = DateUtils.format(new Date(time), DateUtils.DATE_TIME_PATTERN[DateUtils.DATE_TIME_PATTERN.length-1]);
        String fileName = MysqlImportUtil.dbName+"-"+ date;
        String url ="http://47.105.144.190:28082/sqlbak/db_sanitation/"+fileName+".sql";
        // 临时文件
        String osName = System.getProperty("os.name");
        String filePath;
        if (osName.toLowerCase().contains("windows")){
            filePath = "c:/dbreduction.sql";
        } else {
            filePath = "/dbreduction.sql";
        }
        InputStream inputStream = null;
        BufferedInputStream bif = null;
        BufferedOutputStream bof = null;
        try {
            inputStream = MysqlImportUtil.getInputStreamByUrl(url);
            bif = new BufferedInputStream(inputStream);
            bof = new BufferedOutputStream(new FileOutputStream(filePath));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bif.read(bytes)) != -1){
                bof.write(bytes,0,len);
                bof.flush();
            }
            // 开始还原数据库
            MysqlImportUtil.load(filePath);

            bif.close();
            bof.close();

            // 删除文件
            File tempFile = new File(filePath);
            if (tempFile.exists()){
                if (tempFile.delete()){
                    System.out.println(tempFile.getName() + " 文件已被删除！");
                }else {
                    System.out.println("文件删除失败！");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            try {
                bif.close();
                bof.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Result();
    }
}
